<template>
    <div>
        <div class="filter-container">
        <common-input type="number" @keyup.enter.native="handleFilter" class="w100" placeholder="商品编号" v-model="listQuery.productNo" />
        <common-input @keyup.enter.native="handleFilter" class="w100 ml10" placeholder="商品名称" v-model="listQuery.keyword" />
            <el-select class="ml10" @change="getCateList(false)" size="mini" v-model="listQuery.parentCateId" placeholder="一级分类">
                <el-option
                        v-for="item in parentCateList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
            </el-select>
            <el-select size="mini" class="ml10" v-model="listQuery.cateId" placeholder="二级分类">
                <el-option
                        v-for="item in cateList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
            </el-select>
            <el-button size="mini" class="ml10" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
            <el-button class="ml10" size="mini" type="primary" @click="exportExcel">导出</el-button>
            <el-button class="ml10" size="mini" type="primary" @click="syncProduct">同步上下架</el-button>
        </div>
        <el-tabs size="mini" :before-leave='leaveTab' v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="全部" name="0"></el-tab-pane>
        <el-tab-pane label="出售中" name="1"></el-tab-pane>
        <!-- <el-tab-pane label="已售罄" name="2"></el-tab-pane> -->
        <el-tab-pane label="待售中" name="3"></el-tab-pane>
        </el-tabs>
        <el-alert
                v-if="!isSelect&&ids&&ids.length>0"
                show-icon>
            <template slot="title">
                <span>已选择 {{ids.length}} 项</span> <el-button @click="clear()" type="text">清空</el-button> <el-button v-if="activeName=='1'||activeName=='0'" @click="down()" type="text">批量下架</el-button> <el-button v-if="activeName=='3'||activeName=='0'" @click="up()" type="text">批量上架</el-button>
            </template>
        </el-alert>
        <el-table ref="dataTable" :height="tableHeight" :data="list"
                            @sort-change="tblSort"
                            @selection-change="selectChange"
                    style="width: 100%">
                <el-table-column
                        fixed
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column align="right" width="80" label="排序" sortable="custom" prop="order_num">
                    <template slot-scope="scope">
                        <span>{{scope.row.orderNum}}</span>
                        <i v-if="!isSelect" @click="editOrder(scope.row)" class="el-icon-edit ml10" style="cursor:pointer;color:#F4222D;"></i>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="商品编号" >
                    <template slot-scope="scope">
                        <span>{{scope.row.id}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="" width="120">
                    <template slot-scope="scope">
                        <span><img :src="scope.row.listImgUrl" style="width:80px;cursor:pointer;" @click="viewPic(scope.row)" /></span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="商品">
                    <template slot-scope="scope">
                        <div>
                            {{scope.row.title}}
                            <p style="color:red;margin-top:3px;" v-if="!scope.row.market&&scope.row.alibabaReason">{{ scope.row.alibabaReason }}</p>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column width="100" align="right" label="供货价" sortable="custom" prop="min_supply_price">
                    <template slot-scope="scope">
                        <span>￥{{scope.row.minSupplyPrice}}</span>
                    </template>
                </el-table-column>
                <el-table-column width="100" align="right" label="物流成本" sortable="custom" prop="freight_price">
                    <template slot-scope="scope">
                        <span>￥{{scope.row.freightPrice}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="审核通过时间" width="150" sortable="custom" prop="check_at">
                    <template slot-scope="scope">
                        <span>{{scope.row.checkAt}}</span>
                    </template>
                </el-table-column>
                <el-table-column width="100" align="right" label="库存" sortable="custom" prop="inventory">
                    <template slot-scope="scope">
                        <span>{{scope.row.inventory}}</span>
                        <i v-if="!isSelect" @click="editStock(scope.row)" class="el-icon-edit ml10" style="cursor:pointer;color:#F4222D;"></i>
                    </template>
                </el-table-column>
                <el-table-column width="100" align="right" label="实际销量" sortable="custom" prop="sale_count">
                    <template slot-scope="scope">
                        <span>{{scope.row.saleCount}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="200"
                        fixed="right">
                    <template slot-scope="scope">
                        <span v-if="!isSelect">
                            <el-button type="text" @click="handleDetail(scope.row)">查看</el-button>
                            <el-button v-if="scope.row.canEdit==1" type="text" @click="handleUpdate(scope.row)">编辑</el-button>
                            <el-button v-if="scope.row.canUp==1" type="text" @click="handleUp(scope.row)">上架</el-button>
                            <el-button v-if="scope.row.canDown==1" type="text" @click="handleDown(scope.row)">下架</el-button>
                        </span>
                        <span v-else>
                            <el-button type="text" @click="okSelect(scope.row)">选择</el-button>
                        </span>
                    </template>
                </el-table-column>
        </el-table>
            <div class="pagination-container">
                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum" :page-sizes="[20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
            </div>

        <el-dialog title="编辑排序" :visible.sync="dialogOrderVisible" :close-on-click-modal="false" width="300px">
            <el-form :model="orderForm" ref="orderForm" label-width="80px">
                <el-form-item label="排序" prop="orderNum">
                    <el-input size="mini" type="number" placeholder="" maxlength="3" v-model="orderForm.orderNum" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="dialogOrderVisible=false">取消</el-button>
                <el-button :loading="orderLoading" size="mini" type="primary" @click="okOrder">确定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="编辑库存" :visible.sync="dialogStockVisible" :close-on-click-modal="false" width="700px">
            <el-form :model="productForm" ref="productForm" label-width="120px">
                <el-form-item label="商品库存：" prop="inventory">
                    <el-input type="number" size="mini" class="w100"  v-model="productForm.inventory" placeholder="" :disabled="productForm.hasSku==1" />
                </el-form-item>
                <el-form-item label="规格明细：" v-show="productForm.hasSku==1">
                    <div style="width:100%;height:400px;overflow:auto;">
                        <table id="product-attribute-table" class="ikd-input-table ik-table-layout-fixed">
                            <thead>
                            <tr>
                                <th nowrap></th>
                                <th nowrap>规格名</th>
                                <th nowrap>规格值</th>
                                <th nowrap>库存</th>
                            </tr>
                            </thead>
                            <tbody>
                                <template v-for="(item, idx) in productForm.skuInfo">
                                    <tr :key="item.id">
                                        <td nowrap>
                                            {{ idx+1 }}
                                        </td>
                                        <td nowrap>{{ item.name }}</td>
                                        <td nowrap>{{ item.value }}</td>
                                        <td><el-input size="mini" type="number" @blur="makeMinStock" v-model="item.inventory" /></td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>

                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="dialogStockVisible=false">取消</el-button>
                <el-button :loading="stockLoading" size="mini" type="primary" @click="okStock">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import {
        product_list,
        product_delete,
        product_update_order,
        product_detail,
        product_update_stock,
        product_up,
        product_down,
        productExport,
        product_sync
    } from '../../api/product';
    import {
        agency_categories,
        agency_isJd
    } from '../../api/agency';
    import Viewer from 'viewerjs';
    import 'viewerjs/dist/viewer.css';

    export default {
        name: 'product-list',
        components: {
        },
        props: {
            formData: Object
        },
        computed: {
        },
        watch: {
            formData: {
                immediate: true,
                handler (val) {
                    this.isSelect = val.isSelect;
                }
            }
        },
        data() {
            return {
                isJd: false,
                viewerId: null,
                isSelect: false,
                orderLoading: false,
                tableHeight: 200,
                cateList: [],
                parentCateList:[],
                list: null,
                listLoading: true,
                listQuery: {
                    pageNum: 1,
                    pageSize: 20,
                    keyword: undefined,
                    auditStatus: '3',
                    orderCol: "",
                    orderAsc: "",
                    cateId: undefined,
                    parentCateId: undefined,
                    status: '0',
                    getSaleCount: 1,
                    productNo: undefined,
                },
                total: null,
                activeName: '0',
                currentId: 0,
                checkLoading: false,
                dialogOrderVisible: false,
                orderForm: {
                    id: 0,
                    orderNum: 0,
                },
                productForm: {
                    id: 0,
                    hasSku: 0,
                    skuInfo: [],
                    inventory: 0,
                },
                dialogStockVisible: false,
                stockLoading: false,
                ids: []
            }
        },
        mounted() {
            const that = this

            window.onresize = () => {

                return (() => {

                    that._getTableHeight()

                })()
            }
        },
        created() {
            if(this.$route.query.tab) {
                this.activeName = this.$route.query.tab
                this.listQuery.status = this.activeName;
            }
            if(this.$route.query.pageNum) {
                this.listQuery.pageNum = this.$route.query.pageNum
                if(!this.listQuery.pageNum) {
                    this.listQuery.pageNum = 1;
                }
            }
            this._getTableHeight();
            this.getIsJd();
            this.getParentCateList();
            this.getList();
        },
        methods: {
            syncProduct() {
                this.$confirm('确定同步?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        product_sync()
                            .then(() => {
                                this.$message.success("商品状态已同步");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            getIsJd() {
                agency_isJd().then((res)=>{
                    this.isJd = res.data == "1";
                }).catch((err)=>{

                })
            },
            okSelect(item) {
                this.$emit("okSelect", item)
            },
            _getTableHeight() {
                this.tableHeight = window.innerHeight - 250
            },
            getList() {
                this.listLoading = true;
                product_list(this.listQuery).then(response => {
                    this.list = response.data.list;
                    this.total = response.data.total;
                    this.listLoading = false;
                })
            },
            getParentCateList() {
                agency_categories(0).then((res)=>{
                    this.parentCateList = res.data;
                    this.cateList = []
                }).catch((err)=>{
                    this.parentCateList = []
                    this.cateList = []
                });
            },
            getCateList() {
                this.listQuery.cateId = undefined;
                agency_categories(this.listQuery.parentCateId).then((res)=>{
                    this.cateList = res.data;
                }).catch((err)=>{
                    this.cateList = []
                });
            },
            handleFilter() {
                this.listQuery.pageNum = 1;
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.pageNum = val;
                this.getList();
            },
            handleClick(tab, event) {
                this.listQuery.status = this.activeName;
                this.handleFilter();
            // console.log(this.activeName)
            },
            leaveTab(activeName, oldActiveName) {
            // console.log(activeName)
            // return false;
            },
            handleUpdate(row) {
                this.$router.push("/goods_edit?id=" + row.id + "&from=" + encodeURIComponent("goods_list?tab=" + this.activeName + "&pageNum=" + this.listQuery.pageNum)) 
                // this.$router.push("/goods_edit?id=" + row.id + "&from=" + encodeURIComponent(this.$router.currentRoute.name)) 
            },
            handleDelete(row) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        product_delete([row.id])
                            .then(() => {
                                this.$message.success("商品删除成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            handleDetail(row) {
                let {href} = this.$router.resolve({path: '/goods_detail?id=' + row.id});
                window.open(href, '_blank');
            },
            dialogClose() {
                this.$refs.form.resetFields();
            },
            tblSort(d) {
                this.listQuery.orderCol = d.prop;
                this.listQuery.orderAsc = d.order;

                this.handleFilter();
            },
            editOrder(row) {
                this.orderForm.id = row.id;
                this.orderForm.orderNum = row.orderNum;

                // console.log(this.orderForm)
                this.dialogOrderVisible = true;
            },
            okOrder() {
                this.orderLoading = true;
                product_update_order(this.orderForm).then((res)=>{
                    this.orderLoading = false;
                    this.dialogOrderVisible = false;
                    this.$message.success("排序已更新");

                    this.getList();
                }).catch((err)=>{
                    this.orderLoading = false;
                })
            },
            editStock(row) {
                product_detail(row.id).then((res)=>{
                    this.productForm.id = res.data.id;
                    this.productForm.hasSku = res.data.hasSku;
                    this.productForm.inventory = res.data.inventory;
                    this.productForm.skuInfo = res.data.skuInfo;

                    this.dialogStockVisible = true;

                    console.log(this.productForm)
                }).catch((err)=>{

                })
            },
            makeMinStock() {
                let p = 0;
                if(this.productForm.skuInfo && this.productForm.skuInfo.length > 0) {
                    this.productForm.skuInfo.forEach((item)=>{
                        if(item.inventory) {
                            p += Number(item.inventory) || 0
                        }
                    })
                }
                this.productForm.inventory = p;
            },
            okStock() {
                this.stockLoading = true;
                product_update_stock(this.productForm).then((res)=>{
                    this.stockLoading = false;
                    this.dialogStockVisible = false;
                    this.$message.success("库存已更新");

                    this.getList();
                }).catch((err)=>{
                    this.stockLoading = false;
                })
            },
            selectChange(selection) {
                this.ids = [];
                if(selection && selection.length > 0) {
                    selection.forEach((item)=>{
                        this.ids.push(item.id)
                    })
                }
                // console.log(this.ids)
            },
            clear() {
                this.$refs.dataTable.clearSelection();
            },
            up(ids) {
                if(!ids || ids.length < 1) {
                    ids = this.ids;
                }
                this.$confirm('确定上架?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        product_up({
                            ids: ids
                        })
                            .then(() => {
                                this.$message.success("商品上架成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            down(ids) {
                if(!ids || ids.length < 1) {
                    ids = this.ids;
                }
                this.$confirm('确定下架?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        product_down({
                            ids: ids
                        })
                            .then(() => {
                                this.$message.success("商品下架成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            handleUp(row) {
                this.up([row.id]);
            },
            handleDown(row) {
                this.down([row.id]);
            },
            viewPic(row) {
                if(row.imgUrls) {
                    let all_pic = row.imgUrls.split(",");
                    $("#pic_viewer").html("");
                    if(all_pic && all_pic.length > 0) {
                        all_pic.forEach((item, idx)=>{
                            var str  = '<li style="width:100%;">';
                            str += '<img rel-src="' + item + '" src="' + item + '">';
                            str += '</li>';
                            $("#pic_viewer").append(str);
                        })
                    }
                    this.viewerId && this.viewerId.destroy()
                    this.viewerId = new Viewer(document.getElementById('pic_viewer'));
                    $('#pic_viewer').find("img").eq(0).trigger("click")
                }
            },
            createCellPos(n) {
                var ordA = 'A'.charCodeAt(0);

                var ordZ = 'Z'.charCodeAt(0);

                var len = ordZ - ordA + 1;

                var s = "";



                while( n >= 0 ) {

                    s = String.fromCharCode(n % len + ordA) + s;

                    n = Math.floor(n / len) - 1;

                }

                return s;

            },
            exportExcel() {
                productExport(this.listQuery).then((res)=>{
                    if(res.data.items && res.data.items.length > 0) {
                        let items = res.data.items;

                        let export_config = res.data.exportConfig;
                        items.unshift(export_config.header)

                        var column = null;
                        eval("column = " + export_config.columnJs);
                        console.log(column)
                        let export_data = LAY_EXCEL.filterExportData(items, column);
                        let sheet_data = new Object();
                        eval("sheet_data." + res.data.sheet + "=export_data;");
                        let cellPos = this.createCellPos(parseInt(export_config.columnCount) - 1);

                        LAY_EXCEL.setExportCellStyle(export_data, "A1:" + cellPos + "1", {
                            s: {
                                fill: { fgColor: { rgb: "FFFF00" } },
                                alignment: {
                                    horizontal: 'center',
                                    vertical: 'center'
                                },
                                font: {
                                    sz: 12,
                                    bold: true
                                }
                            }
                        });

                        LAY_EXCEL.exportExcel(sheet_data, res.data.fileName, 'xlsx', {
                            extend: {
                                '!merges': export_config.mergeCells,
                                '!cols': export_config.width,
                                '!rows': LAY_EXCEL.makeRowConfig({
                                    1: 40
                                })
                            }
                        });
                    } else {
                        this.$message.error("导出数据为空");
                    }
                }).catch((err)=>{
                    console.log(err)
                })
            }

        }
    }
</script>